package com.zksite.nator.processor.http.container;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zksite.nator.common.container.ChannelContainer;
import com.zksite.nator.common.util.JedisClient;

import io.netty.channel.Channel;

@Component("defaultClientContainer")
public class DefaultClientContainer implements ChannelContainer {

	private Map<String, Channel> container = new ConcurrentHashMap<String, Channel>();

	private static final String CLIENT_LIST = "nator:client:list";

	@Autowired
	private JedisClient jedisClient;

	public void closeChannel(Channel channel) {
		List<String> list = new ArrayList<>();
		for (Map.Entry<String, Channel> me : container.entrySet()) {
			Channel value = me.getValue();
			if (value.id().equals(channel.id())) {
				list.add(me.getKey());
			}
		}
		for (String key : list) {
			remove(key);
			jedisClient.hdel(CLIENT_LIST, key);
		}
	}


	private boolean check(String key) {
		return container.containsKey(key);
	}

	@Override
	public void put(String key, Channel channel) {
		if (check(key)) {
			throw new IllegalStateException("已存在的域名映射." + key);
		}
		jedisClient.hset(CLIENT_LIST, key, channel.id().asLongText());
		container.put(key, channel);
	}

	@Override
	public void remove(String key) {
		container.remove(key);
	}

	@Override
	public Channel get(String key) {
		return container.get(key);
	}

	@Override
	public void remove(Channel channel) {

	}

}
